package com.lenovo.newsapp.activity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.adobe.mobile.Analytics;
import com.adobe.mobile.Config;
import com.lenovo.newsapp.R;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.HttpUtil;
import com.lenovo.newsapp.util.PreferenceUtil;

public class BaseActivity extends ActionBarActivity {

	static final String LOGOUT_ACTION = "lenovo_logout.action";
	ProgressDialog pd;
	ProgressBar loadProgressBar;
	final Handler handler = new Handler();
	boolean success = true;
	public ActionBar actionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);

		actionBar.setBackgroundDrawable(this.getBaseContext().getResources()
				.getDrawable(R.drawable.BarBg));
		
		PreferenceUtil.init(this);
		
//		actionBar.setDisplayHomeAsUpEnabled(false);
//		actionBar.setLogo(R.drawable.new_back);

		setOverflowShowingAlways();
		// actionbar 颜色
		int titleId = Resources.getSystem().getIdentifier("action_bar_title",
				"id", "android");
		TextView tv = (TextView) findViewById(titleId);
		tv.setTextColor(Color.BLACK);

//		if (!checkNetWorkIsAvailable()) {
//			showShortToast(R.string.can_not_connect_server);
//		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(LOGOUT_ACTION);
		this.registerReceiver(this.broadcastReceiver, filter);
		
		Analytics.trackState("BaseActivity", null);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Config.pauseCollectingLifecycleData();
	}
	
	// 始终显示overflow
	private void setOverflowShowingAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKeyField.setAccessible(true);
			menuKeyField.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 显示icon
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		Log.v("baseactivity", "onMenuOpened...");
		if(null != menu && menu.size() == 2){
			menu.getItem(0).setTitle(R.string.action_refresh);
			menu.getItem(1).setTitle(R.string.action_settings);
		}
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod(
							"setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
				}
			}
		}
		return super.onMenuOpened(featureId, menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Config.collectLifecycleData();
//		if (!checkNetWorkIsAvailable()) {
//			showShortToast(R.string.can_not_connect_server);
//		}
	}

	void finishLogoutActivity() {
		Intent intent = new Intent();
		intent.setAction(LOGOUT_ACTION);
		this.sendBroadcast(intent);
	}

	@Override
	protected void onDestroy() {
		this.unregisterReceiver(this.broadcastReceiver);
		super.onDestroy();
	}

	final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(LOGOUT_ACTION)) {
				finish();
			}
		}
	};

	protected void switchLanguage(String language) {
		Log.v(Const.DEBUG, "switchLanguage--" + language);

		Resources resources = getResources();
		Configuration config = resources.getConfiguration();

		// 屏幕
		DisplayMetrics dm = resources.getDisplayMetrics();
		if (language.equals("ch")) {
			config.locale = Locale.SIMPLIFIED_CHINESE;
		} else {
			config.locale = Locale.ENGLISH;
		}
		resources.updateConfiguration(config, dm);

		// 保存
		PreferenceUtil.commitString("language", language);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (null != pd && pd.isShowing()) {
				pd.dismiss();
				pd = null;
			} else {
				finishWithAnimation();
			}
			return true;
		} else
			return super.onKeyDown(keyCode, event);
	}

	/**
	 * 检测网络是否可用
	 * 
	 * @return
	 */
	protected boolean checkNetWorkIsAvailable() {
		return HttpUtil.isNetworkAvailable(this);
	}

	/**
	 * 以动画方式启动新的Actvity
	 * 
	 * @param intent
	 */
	public void startActivityWithAnimation(Intent intent) {
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	/**
	 * 以动画方式启动新的Actvity
	 * 
	 * @param intent
	 */
	public void startActivityWithAnimation(Class<? extends Activity> clazz) {
		startActivity(new Intent(this, clazz));
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	/**
	 * 以动画方式finish()Actvity
	 * 
	 * @param intent
	 */
	public void finishWithAnimation() {
		finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}

	/**
	 * 隐藏软键盘
	 * 
	 * @param v
	 */
	public void hideSoftInput(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	protected void showLoadProgressBar() {
		loadProgressBar = (ProgressBar) findViewById(R.id.loading_progressbar);
		loadProgressBar.setVisibility(View.VISIBLE);
	}

	protected void hideLoadProgressBar() {
		loadProgressBar.setVisibility(View.GONE);
	}

	public void showShortToast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	public void showShortToast(int resId) {
		Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
	}

	public void showLongToast(String str) {
		Toast.makeText(this, str, Toast.LENGTH_LONG).show();
	}

	public void showLongToast(int resId) {
		Toast.makeText(this, resId, Toast.LENGTH_LONG).show();
	}

	/**
	 * 消息提示框（含标题、信息和确认按钮）
	 * 
	 * @param context
	 * @param title
	 * @param message
	 */
	public void showAlert(Context context, String message) {
		new Builder(context).setTitle("提示").setMessage(message)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						arg0.dismiss();
					}
				}).show();
	}

}
